package com.kc.demo.kcapidemo.utils;
/**
 * @标题: HttpClientUtil.java
 * @包名： com.kuangchi.util
 * @功能描述：TODO
 * @作者： jiao.wu
 * @创建时间： 2018年4月30日 下午5:44:03
 * @version v1.0
 */


import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @version v1.0
 * @类描述：http链接工具类
 * @项目名称：sits-face-api @包名： com.kuangchi.util
 * @类名称：HttpClientUtil
 * @创建人：jiao.wu
 * @创建时间：2018年4月30日下午5:44:03
 * @修改人：jiao.wu
 * @修改时间：2018年4月30日下午5:44:03 @修改备注：
 * @Copyright
 */

public class HttpClientUtil {

    private static HttpClientUtil instance = null;

    private HttpClientUtil() {
    }

    public static HttpClientUtil getInstance() {
        if (instance == null) {
            instance = new HttpClientUtil();
        }
        return instance;
    }

    /**
     * @描述:获取请求模板信息
     * @方法名: getRestTemplate
     * @返回类型 RestTemplate
     * @创建人 jiao.wu
     * @创建时间 2018年5月2日上午10:05:56
     * @修改人 jiao.wu
     * @修改时间 2018年5月2日上午10:05:56
     */
    public static RestTemplate getRestTemplate() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectionRequestTimeout(1000);
        factory.setReadTimeout(10000);
        factory.setConnectTimeout(1000);
        factory.setBufferRequestBody(false);
        return new RestTemplate(factory);
    }


    public static RestTemplate getSllRestTemplate() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        HttpComponentsClientHttpRequestFactory factory = generateHttpRequestFactory();
        factory.setConnectionRequestTimeout(1000);
        factory.setReadTimeout(10000);
        factory.setConnectTimeout(1000);
        factory.setBufferRequestBody(false);
        return new RestTemplate(factory);
    }


    public static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        };
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new NoopHostnameVerifier());
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
        CloseableHttpClient httpClient = httpClientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        return factory;
    }

    /**
     * 发送 post请求
     *
     * @param httpUrl 地址
     * @param params  参数(格式:key1=value1&key2=value2)
     */
    public String sendHttpPost(String httpUrl, String params, Map<String, String> headerParams)
            throws Exception {
        RestTemplate restTemplate = getRestTemplate();
        HttpHeaders headers = new HttpHeaders();

        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        if (null != headerParams) {
            for (Entry<String, String> entry : headerParams.entrySet()) {
                headers.add(entry.getKey(), entry.getValue());
            }
        }
        HttpEntity<String> requestEntity = new HttpEntity<String>(params, headers);
        ResponseEntity<String> response = restTemplate.exchange(httpUrl, HttpMethod.POST, requestEntity, String.class);
        return response.getBody();
    }

    /**
     * 发送 post请求
     *
     * @param httpUrl 地址
     * @param params  参数(格式:key1=value1&key2=value2)
     */
    public String sendHttpPost(String httpUrl, String params, MediaType contentType) throws Exception {
        RestTemplate restTemplate = getRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(contentType);

        HttpEntity<String> requestEntity = new HttpEntity<String>(params, headers);
        ResponseEntity<String> response = restTemplate.exchange(httpUrl, HttpMethod.POST, requestEntity, String.class);
        return response.getBody();
    }

    /**
     * @描述:发送get请求
     * @方法名: sendHttpGet
     * @返回类型 String
     * @创建人 jiao.wu
     * @创建时间 2018年5月2日上午10:19:40
     * @修改人 jiao.wu
     * @修改时间 2018年5月2日上午10:19:40
     */
    public String sendHttpGet(String httpUrl) {
        RestTemplate restTemplate = getRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(httpUrl, HttpMethod.GET, requestEntity, String.class);
        return response.getBody();
    }

    public String sendHttpGet(String httpUrl, Map<String, String> header) {
        RestTemplate restTemplate = getRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        header.forEach((k, v) -> {
            headers.add(k, v);
        });
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(httpUrl, HttpMethod.GET, requestEntity, String.class);
        return response.getBody();
    }


}
